package com.renaud.solr.beanTest;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

import fr.insee.solr.model.SolrResponse;
import fr.insee.solr.model.param.SolrFacetParams;
import fr.insee.solr.model.param.SolrRequestParam;
import fr.insee.solr.repository.SolrJConnector;
import fr.insee.solr.repository.SolrRepository;
import fr.insee.solr.service.impl.SolrInseeException;

public class MainShow {

	private static EmbeddedSolrServer server;

	private static SolrRepository<AvisClient> repository;

	// @BeforeClass
	public static void beforeClass() throws IOException {
		clean();
		CoreContainer container = new CoreContainer("src/test/resources/solr");
		container.load();
		server = new EmbeddedSolrServer(container, "avisClient");
		repository = new AvisClientRepository();
		((SolrJConnector<AvisClient>) repository).setServer(server);

	}

	// @AfterClass
	public static void afterClass() throws IOException {
		server.shutdown();
		clean();
	}

	private static void clean() throws IOException {
		File f = new File("src/test/resources/solr/avisClient/data");
		if (f.isDirectory()) {
			FileUtils.cleanDirectory(f);
		}
	}

	// @Test
	public void test() throws SolrInseeException, JsonGenerationException, JsonMappingException, IOException {

		for (int i = 0; i < 10; i++) {
			AvisClient a = AvisBuilder.build();
			repository.index(a);
		}

		SolrRequestParam rp = new SolrRequestParam();
		rp.setQ("*:*");
		SolrFacetParams f = new SolrFacetParams();
		f.setField("speudo");
		f.setLimit(5);
		rp.addFacetField(f);

		SolrResponse<AvisClient> reponse = repository.find(rp);

		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(Feature.INDENT_OUTPUT, true);

		String json = mapper.writeValueAsString(reponse);

		System.out.println(json);

	}
}
